#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

using namespace std;
// 定义条件变量以及一个互斥锁 ,全局的互斥锁和条件变量就这样定义就行
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int tickets = 1000;
void *start_routine(void *args)
{
    
    string name = static_cast<char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        // 在中间开始进行等待消费
        pthread_cond_wait(&cond, &mutex); // 后面必须跟一个互斥锁
        cout<<name << " -->" << tickets << endl;
        tickets--;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    //通过条件变量来控制线程的运行
    pthread_t t[5];
    // 创建子线程
    for (int i = 0; i < 5; i++)
    {
        char *namebuffer = new char[64];
        snprintf(namebuffer, 64, "thread %d", i + 1);
        // 创建线程
        pthread_create(t + i, nullptr, start_routine,namebuffer);
    }
    // 生产者开始进行生产
    while (true)
    {
        sleep(1);
        pthread_cond_signal(&cond);
        cout << "main thread wakeup one thread..." << endl;
    }

    // 回收子线程
    for (int i = 0; i < 5; i++)
    {
        pthread_join(t[i], nullptr);
    }
    return 0;
}